package com.wang.jmonkey.common.config;

import com.wang.jmonkey.common.handler.file.FileSystemHandlerManager;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AspectJTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

public class FileSystemHandlerImportSelector implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        final ClassPathScanningCandidateComponentProvider classPathScanningCandidateComponentProvider = new ClassPathScanningCandidateComponentProvider(false);

        List<TypeFilter> list = new ArrayList<TypeFilter>();
        list.add(new AspectJTypeFilter("com.wang.jmonkey.common.handler..*" , this.getClass().getClassLoader()));

        if (!ObjectUtils.isEmpty(list)) {
            list.forEach(t -> {
                classPathScanningCandidateComponentProvider.addIncludeFilter(t);
            });
            classPathScanningCandidateComponentProvider.findCandidateComponents("com.wang.jmonkey.common.handler.file").forEach(bd -> {
                if (FileSystemHandlerManager.class.getName().equals(bd.getBeanClassName())) {
                    bd.setScope("prototype");
                }

                registry.registerBeanDefinition(bd.getBeanClassName(), bd);
            });
        }
    }
}
